# coding=utf-8
# author=haishan09@gmail.com
from __future__ import unicode_literals
import json
from django.db import models
from custom.fields import JsonifyConfigField
from common.provider import provider_manager


class Widget(models.Model):
    name = models.CharField('名称', max_length=64)
    label = models.CharField('说明', max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.label


class Provider(models.Model):
    name = models.CharField('名称', max_length=64)
    label = models.CharField('说明', max_length=64)
    config = JsonifyConfigField('配置信息', default='{}', blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.label

    def get_instance(self, dim):
        provider_cls = provider_manager.get_provider('dimension', self.name)
        return provider_cls(self.config, dim)

class Dimension(models.Model):
    name = models.CharField('名称', max_length=64)
    label = models.CharField('说明', max_length=64)
    dtype = models.IntegerField(
        '是否日期类型',
        choices=((0, '非日期类型'), (1, '日期类型')), 
        default=0)
    provider = models.ForeignKey(Provider)
    config = JsonifyConfigField('配置信息', default='{}', blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.label + ' (' + self.name + ')'

    @property
    def dconf(self):
        return json.loads(self.config)

    def get_choices(self, cuts={}):
        return self.provider.get_instance(self).get_choices(cuts=cuts)

    @property
    def choices_uri(self):
        return '/dimension/{0}/choices/'.format(self.pk)

    @property
    def provider_instance(self):
        return self.provider.get_instance(self)
